#!/bin/bash
# Author: MeiLongWei <weimeilong@baidu.com>
# Create Date: 2022-02-07 11:12:32
# Last Modified: 2022-02-14 08:21:56
# Description: Noahee/Bcm logclean.


test -d logs || mkdir logs


function clean() {
  local cleanDir
  cleanDir=$1


  find "$cleanDir" -type d -a -name log -o -type l -a -name log | while read -r logDir; do
    # delete debug log default 1 days ago
    cleanLogForLevel $logDir min  10080 debug
    # delete info log default 1 days ago
    cleanLogForLevel $logDir min  10080 info
    # delete access log default 1 days ago
    cleanLogForLevel $logDir min  10080 access
    # delete error log default 15 days ago
    cleanLogForLevel $logDir time 14 error
    # delete warn log default 1 days ago，精确匹配避免与 warning-tracker 服务名重复
    cleanLogForLevel $logDir min 10080 'warn.log|log.warning|warn_'
  done
  echo -e "\033[32mclean done: $cleanDir\033[0m"
}


function clean_bcm_tmp() {
  local logPath
  logPath=logs/$(date +%F).tmp.log
  echo >"$logPath"


  find /tmp \
    -name 'go-ff*'              -o \
    -name 'go-proxy*'           -o \
    -name 'go-alert*'           -o \
    -name 'go-adaptor*'         -o \
    -name 'site-agent*'         -o \
    -name 'conf-puller*'        -o \
    -name 'conf-server*'        -o \
    -name 'conf-adaptor*'       -o \
    -name 'data-adaptor*'       -o \
    -name 'site-controller*'    -o \
    -name 'go-nodata-checker*'  -o \
    -name 'go-warning-tracker*' -a \
    -type f 2>&1 | awk '{print "rm -rf " $1}' >>"$logPath"
  index=0
  head="Delete Percent: "
  arry=("\\" "|" "/" "-")
  total=$(wc -l "$logPath" | awk '{print $1}')
  test -z "$total" && echo -e "\033[32m No log found in /tmp.\033[0m" && exit 0


  while IFS= read -r cmd; do
    percent=$(awk "BEGIN { pc=100*${index:-0}/${total:-100}; i=int(pc); print (pc-i<0.5)?i:i+1 }")
    if [ "$percent" != "${last:-Z}" ]; then
      printf "%s [%-100s] %d%% %c\r" "$head" "$str" "$percent" "${arry[$percent % 4]}"
      str+="#"
    fi
    ((index++))
    last=$percent
    $cmd >&/dev/null
  done <"$logPath"
  echo -e "\n\033[32mclean done: /tmp\033[0m"
}

#清理不同级别日志公共方法
#cleanLogForLevel $logDir min  10080 debug
#-mmin n：查找在 n 分钟内被修改过的文件。-a && -o ||
#find -L "/home/work/bcm/go-ff/log/" -type f -a -name '*log*' -a -mmin +10080
#找到近七天改动的日志文件-》过滤文件名->
#删除7天前的日志
function cleanLogForLevel() {
  find -L "$1" -type f -a -name '*log*' -a -m$2 +$3 | egrep -iE $4 | grep -E "$(date +%Y)|$(date -d last-year +%Y)" |
  while read -r logFile; do
    test -f "$logFile" && rm -f "$logFile" && echo "delete $logFile" >>"logs/$(date +%F).log"
  done
}

clean_bcm_tmp
clean /home/work/bcm

find ./ -maxdepth 1 -type f | xargs ls -t| sed "1,${KEEP_NUM}d" |xargs rm -f
